"""
dict 客户端： 发起请求
"""
import re
import sys
from socket import *

# 服务器地址
ADDR = ("127.0.0.1", 5555)


# 具体发起请求
class Handle:
    # 名字验证:3-10位字母数字下划线构成,不能以数字和开头
    @staticmethod
    def check(name):
        if re.search(r"^[_a-zA-Z][-\w]{2,9}$", name):
            return True
        else:
            return False

    def __init__(self):
        self.sock = self._connect()

    def _connect(self):
        sock = socket()
        sock.connect(ADDR)
        return sock

    # 处理注册
    def do_register(self):
        """
        匹配用户名是否合格
        发送请求注册用户
        """
        user = input("请输入用户名")
        passwd = input("请输入密码")
        if not Handle.check(user):
            print("用户名必须数字下划线字母构成")
            return
        msg = "R\t%s\t%s" % (user, passwd)
        self.sock.send(msg.encode())
        data = self.sock.recv(1024).decode()
        print(data)
        if data == "T":
            print("注册成功")
        elif data == "F":
            print("注册失败")

    # 退出
    def do_exit(self):
        """发送请求退出,结束该进程"""
        self.sock.send(b"E")
        print("退出成功")
        sys.exit()

    # 登录
    def do_login(self):
        """输入账户名,密码发送登录请求"""
        user = input("请输入账户名")
        passwd = input("请输入密码")
        msg = "L\t%s\t%s" % (user, passwd)
        self.sock.send(msg.encode())
        response = self.sock.recv(1024)
        if response == b"T":
            print("登录成功")
            return True
        elif response == b"F":
            print("登录失败")

    # 查询单词,得到解释
    def query_word(self):
        """
        循环输入单词得到解释,输入特殊符号退出该功能
        """
        while True:
            word = input("请输入要查询的单词:")
            if word == "##" or not word:
                break
            msg = "Q\t%s" % word
            self.sock.send(msg.encode())
            response = self.sock.recv(1024)
            if response == b"F":
                print("该单词不存在")
            else:
                print(response.decode())

    # 查看历史记录
    def do_history(self):
        """
        发送请求查单词,
        得到记录列表按分号切割循环打印
        """
        self.sock.send(b"H")
        response = self.sock.recv(1024 * 10)
        data = response.decode().split('\t')
        # ['T', '_思念1,s,2021-10-27 21:16:34;_思念1,a,2021-10-27 21:16:33;']
        if data[0] == "T":
            # data[1] -->;,
            for row in data[1].split(";"):
                print(row)
        else:
            print("您还没有查询记录哦")


class DictView:
    def __init__(self):
        self._handle = Handle()

    # 二级页面选项
    def _menu_2(self):
        while True:
            print("""
    =============  Query =============
     1. 查单词   2. 历史记录   3. 注销
    ==================================
            """)
            cmd = input("请输入选项:")
            if cmd == '1':
                self._handle.query_word()
            elif cmd == '2':
                self._handle.do_history()
            elif cmd == '3':
                break
            else:
                print("请输入正确选项!")
    # 一级页面选项
    def _menu_1(self):
        while True:
            print("""
    =========  Welcome ===========
     1. 注册   2. 登录   3. 退出
    ==============================
            """)
            cmd = input("请输入选项:")
            if cmd == '1':
                self._handle.do_register()
            elif cmd == '2':
                if self._handle.do_login():
                    self._menu_2()
            elif cmd == '3':
                self._handle.do_exit()
            else:
                print("请输入正确选项!")

    # 入口函数调用一级页面
    def main(self):
        self._menu_1()


if __name__ == '__main__':
    dict = DictView()
    dict.main()
